﻿#coding=utf-8
import os,sys
root = os.path.dirname(__file__)
sys.path.insert(0, os.path.join(root, 'lib'))


import web
import hashlib
import xml.etree.ElementTree as ET
from message import TextMsg,ImageMsg,LinkMsg,LocationMsg,SubscribeMsg
from reply import TextReply
config = {"TOKEN":'weixin'}

urls = (
    '/weixin','weixin'
)
app_root = os.path.dirname(__file__)

class weixin:
    def GET(self):
        data = web.input()
        #以下是微信公众平台请求的参数
        signature = data.signature
        timestamp = data.timestamp
        nonce = data.nonce
        echostr = data.echostr
        #自己定义的 TOKEN
        token = config['TOKEN']
        #对微信发送的请求，做验证
        tmplist = [token, timestamp, nonce]
        tmplist.sort()
        tmpstr = ''.join( tmplist )
        hashstr = hashlib.sha1( tmpstr ).hexdigest()
        #如果相等，返回验证信息
        if hashstr == signature:
            return echostr
        #如果不相等，返回错误，并打印调试信息
        print signature,timestamp,nonce
        print tmpstr,hashstr
        return 'Error' + echostr
    def POST(self):
        #接收请求内容
        data = web.data()
        #解析XML内容
        root = ET.fromstring(data)
        msg = {}
        for child in root:
            msg[child.tag] = child.text
        if SubscribeMsg(msg):
            content = u"Hello"
            return TextReply(msg,content)

app = web.application(urls, globals()).wsgifunc()
from bae.core.wsgi import WSGIApplication
application = WSGIApplication(app)